package com.mazaiting.jetpack.architecture.room

import android.arch.persistence.room.Room
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.mazaiting.jetpack.R
import com.mazaiting.log.L
import kotlinx.android.synthetic.main.activity_room.*

class RoomActivity : AppCompatActivity() {
  //  private lateinit var db: AppDatabase
  private lateinit var userDao: UserDao
  
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_room)
    
    btn_create_db.setOnClickListener {
      val db = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "ROOM").build()
      userDao = db.userDao()
    }
    btn_insert.setOnClickListener {
      Thread(Runnable {
        val users = (0..10).map { User(it, "first$it", "last$it") }
        userDao.insertAll(users)
      }).start()
    }
    btn_find_all.setOnClickListener {
      Thread(Runnable {
        userDao.getAll().forEach { L.e(it.toString()) }
      }).start()
    }
    btn_find_id.setOnClickListener {
      Thread(Runnable {
        userDao.loadAllByIds(intArrayOf(0, 1, 2, 3, 4)).forEach { L.e(it.toString()) }
      }).start()
    }
    btn_find_name.setOnClickListener {
      Thread(Runnable {
        L.e(userDao.findByName("first1", "last1").toString())
      }).start()
    }
    btn_update.setOnClickListener {
      Thread(Runnable {
        val user = userDao.findByName("first1", "last1")
        user.firstName = "ma"
        user.lastName = "zaiting"
        userDao.update(user)
        userDao.loadAllByIds(intArrayOf(1)).forEach { L.e(it.toString()) }
      }).start()
    }
    btn_delete.setOnClickListener {
      Thread(Runnable {
        userDao.delete(userDao.loadAllByIds(intArrayOf(0))[0])
      }).start()
    }
  }
}
